import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { ConfigProvider, theme as antdTheme } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { useLocalStorage } from '../hooks';

// 设置 dayjs 的全局 locale 为中文
dayjs.locale('zh-cn');

// 布局类型
export const LAYOUT_TYPES = {
    SIDEBAR: 'sidebar',    // 侧边栏布局
    TOPBAR: 'topbar',      // 顶部菜单布局
    MIXED: 'mixed'         // 混合布局
};

// 主题配色方案
const THEME_COLORS = {
    light: {
        primary: '#1890ff',
        success: '#52c41a',
        warning: '#faad14',
        error: '#ff4d4f',
        bg: '#ffffff',
        bgSecondary: '#f5f5f5',
        text: '#000000',
        textSecondary: '#666666',
        border: '#d9d9d9',
    },
    dark: {
        // 优化的黑暗主题配色
        primary: '#177ddc',
        success: '#49aa19',
        warning: '#d89614',
        error: '#dc4446',
        bg: '#1f1f1f',           // 主背景色
        bgSecondary: '#2d2d2d',  // 次要背景色
        bgElevated: '#363636',   // 悬浮背景色
        text: '#ffffff',
        textSecondary: '#bfbfbf',
        textTertiary: '#8c8c8c',
        border: '#434343',
        borderSecondary: '#303030',
    }
};

const ThemeConfigContext = createContext();

export const useThemeConfig = () => {
    const context = useContext(ThemeConfigContext);
    if (!context) {
        throw new Error('useThemeConfig must be used within ThemeConfigProvider');
    }
    return context;
};

export const ThemeConfigProvider = ({ children }) => {
    const [isDark, setIsDark] = useLocalStorage('theme-dark', false);
    const [layoutType, setLayoutType] = useLocalStorage('layout-type', LAYOUT_TYPES.SIDEBAR);
    const [isLayoutChanging, setIsLayoutChanging] = useState(false);
    const [primaryColor, setPrimaryColor] = useLocalStorage('primary-color', '#1890ff');
    const [showDemoFeatures, setShowDemoFeatures] = useLocalStorage('show-demo-features', true);


    // 更新HTML根元素的class
    useEffect(() => {
        if (isDark) {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    }, [isDark]);


    const toggleTheme = (event) => {
        // 检查浏览器是否支持 View Transitions API
        if (!document.startViewTransition) {
            // 降级方案：使用简单的过渡动画
            document.documentElement.classList.add('theme-transition-fallback');
            setIsDark(!isDark);
            setTimeout(() => {
                document.documentElement.classList.remove('theme-transition-fallback');
            }, 300);
            return;
        }

        // 获取点击位置
        const x = event?.clientX ?? window.innerWidth / 2;
        const y = event?.clientY ?? window.innerHeight / 2;

        // 检测复杂页面并添加优化类
        const hasComplexComponents = document.querySelector('.ant-table, .ant-tabs, .ant-form-item');
        if (hasComplexComponents) {
            document.documentElement.classList.add('theme-switching-complex');
        }

        // 设置自定义CSS属性用于动画
        document.documentElement.style.setProperty('--circle-x', `${x}px`);
        document.documentElement.style.setProperty('--circle-y', `${y}px`);

        // 计算圆形半径
        const radius = Math.sqrt(
            Math.max(x, window.innerWidth - x) ** 2 + Math.max(y, window.innerHeight - y) ** 2
        );
        document.documentElement.style.setProperty('--circle-radius', `${radius}px`);

        // 启动 View Transition
        const transition = document.startViewTransition(() => {
            setIsDark(!isDark);
        });

        // 优化清理机制
        const themeCleanup = () => {
            // 移除优化类
            document.documentElement.classList.remove('theme-switching-complex');
        };

        transition.finished
            .then(() => {
                // 延迟清理，确保复杂组件渲染完成
                setTimeout(() => {
                    themeCleanup();
                }, hasComplexComponents ? 200 : 50);
            })
            .catch((error) => {
                console.warn('View Transition 动画出现问题:', error);
                themeCleanup();
            });

        // 主题切换安全超时
        setTimeout(themeCleanup, hasComplexComponents ? 1000 : 700);
    };

    const changeLayoutWithAnimation = useCallback((newLayoutType, event) => {
        // 严格检查：防止重复点击和无效切换
        if (newLayoutType === layoutType) {
            return; // 已经是当前布局
        }

        if (isLayoutChanging) {
            return; // 切换进行中，忽略点击
        }

        setIsLayoutChanging(true);

        // 检查浏览器是否支持 View Transitions API
        if (!document.startViewTransition) {
            // 降级方案：使用简单的过渡动画
            document.documentElement.classList.add('layout-transition-fallback');
            setTimeout(() => {
                setLayoutType(newLayoutType);
                setTimeout(() => {
                    setIsLayoutChanging(false);
                    document.documentElement.classList.remove('layout-transition-fallback');
                }, 300);
            }, 150);
            return;
        }

        // 获取点击位置
        const x = event?.clientX ?? window.innerWidth / 2;
        const y = event?.clientY ?? window.innerHeight / 2;

        // 设置自定义CSS属性用于动画
        document.documentElement.style.setProperty('--layout-circle-x', `${x}px`);
        document.documentElement.style.setProperty('--layout-circle-y', `${y}px`);

        // 计算圆形半径
        const radius = Math.sqrt(
            Math.max(x, window.innerWidth - x) ** 2 + Math.max(y, window.innerHeight - y) ** 2
        );
        document.documentElement.style.setProperty('--layout-circle-radius', `${radius}px`);

        // 为布局切换添加特殊标识类
        document.documentElement.classList.add('layout-changing');

        // 使用立即执行函数避免闭包问题
        const targetLayout = newLayoutType;

        // 启动 View Transition
        const transition = document.startViewTransition(() => {
            // 直接设置状态，不依赖闭包
            setLayoutType(targetLayout);
        });

        // 创建清理函数
        const performCleanup = () => {
            setIsLayoutChanging(false);
            document.documentElement.classList.remove('layout-changing');
        };

        // 设置动画完成处理
        let cleanupExecuted = false;
        const safeCleanup = () => {
            if (!cleanupExecuted) {
                cleanupExecuted = true;
                performCleanup();
            }
        };

        // 监听 View Transition 完成
        transition.finished
            .then(() => {
                // 等待视觉波动画完整结束 (1s) + 缓冲时间
                setTimeout(() => {
                    safeCleanup();
                }, 1100); // 视觉波1000ms + 100ms缓冲
            })
            .catch((error) => {
                console.warn('布局切换动画出现问题:', error);
                safeCleanup();
            });

        // 安全超时机制 - 防止卡死
        setTimeout(() => {
            safeCleanup();
        }, 1600); // 给足够时间让动画完整播放

    }, [layoutType, isLayoutChanging]); // 依赖当前状态

    // 切换演示功能显示
    const toggleDemoFeatures = (checked) => {
        setShowDemoFeatures(checked);
    };

    const currentColors = isDark ? THEME_COLORS.dark : THEME_COLORS.light;

    // Ant Design 主题配置
    const antdThemeConfig = {
        algorithm: isDark ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
        token: {
            colorPrimary: primaryColor,
            colorSuccess: '#52c41a',
            colorWarning: '#faad14',
            colorError: '#ff4d4f',
            colorInfo: '#1890ff',
            borderRadius: 8,
            wireframe: false,
        },
        components: {
            Layout: {
                headerBg: isDark ? '#001529' : '#ffffff',
                siderBg: isDark ? '#001529' : '#ffffff',
                bodyBg: isDark ? '#141414' : '#f5f5f5',
            },
            Menu: {
                itemBg: 'transparent',
                itemSelectedBg: isDark ? '#1890ff' : '#e6f7ff',
                itemHoverBg: isDark ? '#1890ff33' : '#f0f0f0',
            },
            Card: {
                headerBg: isDark ? '#1f1f1f' : '#fafafa',
            },
            Table: {
                headerBg: isDark ? '#1f1f1f' : '#fafafa',
                rowHoverBg: isDark ? '#1f1f1f' : '#f5f5f5',
            },
        },
    };

    const value = {
        isDark,
        layoutType,
        primaryColor,
        currentColors,
        isLayoutChanging,
        showDemoFeatures,
        LAYOUT_TYPES,
        toggleTheme,
        setLayoutType,
        changeLayoutWithAnimation,
        setPrimaryColor,
        toggleDemoFeatures,
        antdThemeConfig,
    };

    return (
        <ThemeConfigContext.Provider value={value}>
            <ConfigProvider
                theme={antdThemeConfig}
                locale={zhCN}
            >
                {children}
            </ConfigProvider>
        </ThemeConfigContext.Provider>
    );
};

export default ThemeConfigProvider;
